import {useCallback} from 'react';
import {Button} from "antd";
import {useSlate} from "slate-react";
import {Editor, Transforms} from "slate";

const LIST_TYPES = {
  'bulleted-list': 'list-item',
  'ol': 'ol-item',
  'todo-list': 'todo-item'
}

export default (props) => {
  const {children, mark} = props;
  const slate = useSlate();

  const isActive = useCallback(() => {
    const [match] = Editor.nodes(slate, {
      match: n => n.type === mark
    });
    return !!match
  }, [slate, mark]);

  const toggleBlock = useCallback(() => {
    const isList = LIST_TYPES[mark];
    Transforms.unwrapNodes(slate, {
      match: n => LIST_TYPES[n.type],
      split: true
    });

    Transforms.setNodes(slate, {
      type: isActive() ? 'paragraph' : isList ? isList : mark,
      value: {checked: true, endTime: '2020-01-01'}
    });

    if (!isActive() && isList) {
      const block = {type: mark, children: []};
      Transforms.wrapNodes(slate, block)
    }
  }, [slate, mark, isActive]);

  return (
    <>
      {/*<Button onClick={handleClick} type={isActive() ? 'primary': ''}  size={"small"}>*/}
      {/*  {children}*/}
      {/*</Button>*/}
      <Button size={"small"} type={isActive() ? 'primary' : ''} onClick={toggleBlock}>
        {children}
      </Button>
    </>
  )
}
